﻿using MyActor.Interfaces;
using Dapr.Actors;
using Dapr.Actors.Runtime;
using System;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Net;

namespace MyActorService
{
    public class InventoryActor : Actor, IInventory
    {
        private readonly ILogger<InventoryActor> _logger;
        public InventoryActor(ActorHost host, ILogger<InventoryActor> logger) : base(host)
        {
            _logger = logger;
        }

        public int _currentValue = 100;
        DateTime preCall = DateTime.Today;
        /// <summary>     
        /// /// 加 库存(无锁), 该方法单线程执行     
        /// /// </summary>          
        public async Task<string> SubtractAsync(OrderItem orderItem, ActorId actorId)
        {
            //获取的是当前产品的库存        
            //var currentValue = await StateManager.TryGetStateAsync<int>(_currentValue);
            ////无锁扣减库存        
            //var newValue = currentValue.Value + orderItem.Quantity;
            ////更新库存        
            //await StateManager.SetStateAsync(_currentValue, newValue);
            //return newValue;
            string? localIp = NetworkInterface.GetAllNetworkInterfaces()
                .Select(p => p.GetIPProperties())
                .SelectMany(p => p.UnicastAddresses)
                .FirstOrDefault(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address))?.Address.ToString();
             
            var diff = (int)(DateTime.Now - preCall).TotalMilliseconds;
            if (diff < 5000)
            {
                _logger.LogInformation($"请求数量超过配置,当前actor是：{actorId},时间是：{DateTime.Now.ToString("yyyy-MM-dd H-m-ss ffff")}，距离上次毫秒数是：{diff}");
                await Task.Delay(5000 - diff);
            }
            _logger.LogInformation($"正常当前actor是：{actorId},时间是：{DateTime.Now.ToString("yyyy-MM-dd H-m-s ffff")}，距离上次毫秒数是：{diff}");
            preCall = DateTime.Now;
          
            _currentValue = _currentValue - orderItem.Quantity;
            return await Task.FromResult($"当前时间：【{DateTime.Now.ToString("yyyy-MM-dd H-m-s ffff")}】，ActorId =【{actorId}】，当前库存=【{_currentValue}】" );
        }

    }
}
